package cz.muni.fi.pa036.kiss.daoimpl;

import cz.muni.fi.pa036.kiss.Entity.Kolej;
import cz.muni.fi.pa036.kiss.Entity.SluzbaKoleje;
import cz.muni.fi.pa036.kiss.dao.SluzbaKolejeDAO;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

public class SluzbaKolejeDAOImpl implements SluzbaKolejeDAO {

    @PersistenceContext
    private EntityManager em;

    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    @Override
    public void create(SluzbaKoleje sluzba) {
        if (sluzba == null) {
            throw new IllegalArgumentException("sluzba is null");
        }
        if (sluzba.getId() != null) {
            throw new IllegalArgumentException("sluzba.id is not null");
        }

        em.persist(sluzba);
    }

    @Override
    public SluzbaKoleje get(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("null id");
        }
        SluzbaKoleje sluzbaKoleje = em.find(SluzbaKoleje.class, id);
        return sluzbaKoleje;
    }

    @Override
    public void update(SluzbaKoleje sluzba) {
        if (sluzba == null) {
            throw new IllegalArgumentException("sluzba is null");
        }
        if (sluzba.getId() == null) {
            throw new IllegalArgumentException("sluzba.id is null");
        }

        em.merge(sluzba);
    }

    @Override
    public void remove(SluzbaKoleje sluzba) {
        if (sluzba == null) {
            throw new IllegalArgumentException("sluzba is null");
        }
        if (sluzba.getId() == null) {
            throw new IllegalArgumentException("sluzba.id is null");
        }
        SluzbaKoleje c = em.find(SluzbaKoleje.class, sluzba.getId());
        em.remove(c);
    }

    @Override
    public List<SluzbaKoleje> findAll() {
        Query query = em.createQuery("SELECT c FROM SluzbaKoleje c");
        List<SluzbaKoleje> results = query.getResultList();

        return results;
    }

    @Override
    public List<SluzbaKoleje> findByKolej(Kolej kolej) {
        if (kolej == null) {
            throw new IllegalArgumentException("null kolej");
        }
        Long kolej_id = kolej.getId();
        Query query = em.createQuery("SELECT c FROM SluzbaKoleje c WHERE c.kolej.id = kolej_id");
        List<SluzbaKoleje> results = query.getResultList();

        return results;
    }

    @Override
    public List<SluzbaKoleje> findByName(String nazev) {
        if (nazev == null) {
            throw new IllegalArgumentException("null kolej");
        }
        Query query = em.createQuery("SELECT c FROM SluzbaKoleje c WHERE c.nazev = nazev");
        List<SluzbaKoleje> results = query.getResultList();

        return results;
    }
}
